package com.awesome.spring.action.impl;

import com.awesome.spring.action.AccountReduceAction;
import com.awesome.spring.bean.Account;
import com.awesome.spring.service.AccountService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * AccountReduceActionImpl
 *
 * @author alex wu
 * @date 2023/10/16
 */
@Slf4j
@Component
public class AccountReduceActionImpl implements AccountReduceAction {

    @Autowired
    private AccountService accountService;

    @Override
    public boolean reduce(String userId, int money) {
        UpdateWrapper<Account> up = new UpdateWrapper<>();
        String sql = "money = money - " + money;
        up.setSql(sql);
        up.eq("user_id", userId);
        accountService.update(up);
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext businessActionContext) {
        String userId = String.valueOf(businessActionContext.getActionContext("userId"));
        System.out.println(userId);
        log.info("提交成功");
        return true;
    }

    @Override
    public boolean cancel(BusinessActionContext businessActionContext) {
        String userId = String.valueOf(businessActionContext.getActionContext("userId"));
        int money = (int) businessActionContext.getActionContext("money");
        LambdaQueryWrapper<Account> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Account::getUserId, userId);
        Account account = accountService.getOne(lqw);

        UpdateWrapper<Account> uw = new UpdateWrapper<>();
        uw.set("money", account.getMoney() + money);
        uw.eq("user_id", userId);
        accountService.update(uw);
        log.info("回滚成功");
        return true;
    }
}
